// @File  : influxdb.go
// @Author: JunLong.Liao&此处不应有BUG!
// @Date  : 2021/6/1
// @slogan: 又是不想写代码的一天，神兽保佑，代码无BUG！
//         ┏┓      ┏┓
//        ┏┛┻━━━━━━┛┻┓
//        ┃     ღ    ┃
//        ┃  ┳┛   ┗┳ ┃
//        ┃     ┻    ┃
//        ┗━┓      ┏━┛
//          ┃      ┗━━━┓
//          ┃ 神兽咆哮!  ┣┓
//          ┃         ┏┛
//          ┗┓┓┏━━━┳┓┏┛
//           ┃┫┫   ┃┫┫
//           ┗┻┛   ┗┻┛

package DB

import (
	"context"
	"fmt"
	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
)

func InfluxDB() {
	// You can generate a Token from the "Tokens Tab" in the UI
	const token = "KayzAxyKz8xacx0EBZgrlROEKeWKNif9Yd51rV3M18RFwOXJn4l3TuiKrl59HBZ9F8GBT_3N-IGo2rR1IUrwlQ=="
	const bucket = "test"
	const org = "test"

	client := influxdb2.NewClient("http://127.0.0.1:8088", token)
	// always close client at the end
	defer client.Close()

	// get non-blocking write client
	// writeAPI := client.WriteAPI(org, bucket)

	// // write line protocol
	// for i := 0; i < 10; i++ {
	// 	avg := 23 + i
	// 	max := 45 + i
	// 	writeAPI.WriteRecord(fmt.Sprintf("stat,unit=temperature avg=%v,max=%v", avg, max))
	// }
	// // Flush writes
	// writeAPI.Flush()

	query := fmt.Sprintf("from(bucket:\"%v\")|> range(start: -1h) |> filter(fn: (r) => r._measurement == \"stat\")", bucket)
	// Get query client
	queryAPI := client.QueryAPI(org)
	// get QueryTableResult
	result, err := queryAPI.Query(context.Background(), query)
	if err == nil {
		// Iterate over query response
		for result.Next() {
			// Notice when group key has changed
			if result.TableChanged() {
				fmt.Printf("table: %s\n", result.TableMetadata().String())
			}
			// Access data
			fmt.Printf("value: %v\n", result.Record().Value())
		}
		// check for an error
		if result.Err() != nil {
			fmt.Printf("query parsing error: %\n", result.Err().Error())
		}
	} else {
		panic(err)
	}
}
